import React, { useState, useEffect } from "react";
import {
  Form,
  Input,
  Button,
  Select,
  Card,
  message,
  Checkbox,
  Row,
  Col,
  Space,
  Modal,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  PhoneOutlined,
  MailOutlined,
  SafetyOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import { useNavigate, Link } from "react-router-dom";
import { authAPI } from "../../services/api";
import "./Register.scss";

interface RegisterForm {
  name: string;
  phone: string;
  email: string;
  password: string;
  confirmPassword: string;
  role: "teacher" | "student";
  captcha: string;
  smsCode: string;
  agree: boolean;
  // 教师额外字段
  department?: string;
  title?: string;
  subject?: string;
  teacherNo?: string;
  // 学生额外字段
  studentId?: string;
  major?: string;
  className?: string;
  grade?: string;
}

const Register: React.FC = () => {
  const navigate = useNavigate();
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [sendingCode, setSendingCode] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [captchaUrl, setCaptchaUrl] = useState("");
  const [agreementVisible, setAgreementVisible] = useState(false);
  const [selectedRole, setSelectedRole] = useState<"teacher" | "student">(
    "teacher"
  );

  // 加载图形验证码
  const loadCaptcha = () => {
    const timestamp = new Date().getTime();
    setCaptchaUrl(`http://localhost:8080/api/v1/user/notify?t=${timestamp}`);
  };

  useEffect(() => {
    loadCaptcha();
  }, []);

  // 倒计时逻辑
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (countdown > 0) {
      timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
    }
    return () => {
      if (timer) clearTimeout(timer);
    };
  }, [countdown]);

  // 发送短信验证码
  const sendSmsCode = async () => {
    try {
      const phone = form.getFieldValue("phone");
      const captcha = form.getFieldValue("captcha");

      if (!phone) {
        message.error("请先输入手机号");
        return;
      }

      if (!captcha) {
        message.error("请先输入图形验证码");
        return;
      }

      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/;
      if (!phoneRegex.test(phone)) {
        message.error("请输入正确的手机号格式");
        return;
      }

      setSendingCode(true);
      console.log("发送验证码请求:", { phone, captcha });

      const response = await authAPI.sendCode(phone, captcha);
      console.log("发送验证码响应:", response);

      if (response && response.code === 0) {
        message.success("验证码发送成功，请查收短信");
        setCountdown(60);
        loadCaptcha(); // 重新加载图形验证码
      } else {
        const errorMessage =
          response?.msg || response?.message || "验证码发送失败";
        message.error(errorMessage);
        loadCaptcha(); // 重新加载图形验证码
      }
    } catch (error: any) {
      console.error("发送验证码失败:", error);

      // 提供更详细的错误信息
      let errorMessage = "验证码发送失败，请重试";

      if (error?.response?.data) {
        errorMessage =
          error.response.data.msg ||
          error.response.data.message ||
          "验证码发送失败";
      } else if (error?.message) {
        errorMessage = error.message;
      }

      // 特殊错误处理
      if (errorMessage.includes("图形验证码")) {
        errorMessage = "图形验证码错误，请重新输入";
      } else if (errorMessage.includes("手机号")) {
        errorMessage = "手机号格式不正确或已被注册";
      } else if (errorMessage.includes("频繁")) {
        errorMessage = "发送过于频繁，请稍后再试";
      } else if (errorMessage.includes("网络")) {
        errorMessage = "网络连接失败，请检查网络设置";
      }

      message.error(errorMessage);
      loadCaptcha(); // 重新加载图形验证码
    } finally {
      setSendingCode(false);
    }
  };

  // 表单提交
  const onFinish = async (values: RegisterForm) => {
    try {
      setLoading(true);

      const registerData = {
        name: values.name,
        phone: values.phone,
        email: values.email,
        password: values.password,
        code: values.smsCode,
        type: values.role,
        // 添加角色特定字段
        ...(values.role === "teacher" && {
          department: values.department,
          title: values.title,
          subject: values.subject,
          teacherNo: values.teacherNo,
        }),
        ...(values.role === "student" && {
          studentId: values.studentId,
          major: values.major,
          className: values.className,
          grade: values.grade,
        }),
      };

      console.log("注册请求数据:", registerData);

      const response = await authAPI.register(registerData);
      console.log("注册响应:", response);

      if (response && response.code === 0) {
        message.success("注册成功！请登录");
        navigate("/login");
      } else {
        const errorMessage =
          response?.msg || response?.message || "注册失败，请重试";
        message.error(errorMessage);
      }
    } catch (error: any) {
      console.error("注册失败:", error);

      // 提供更详细的错误信息
      let errorMessage = "注册失败，请重试";

      if (error?.response?.data) {
        errorMessage =
          error.response.data.msg ||
          error.response.data.message ||
          "注册失败，请检查输入信息";
      } else if (error?.message) {
        errorMessage = error.message;
      }

      // 特殊错误处理
      if (errorMessage.includes("手机号")) {
        errorMessage = "手机号已被注册或格式不正确";
      } else if (errorMessage.includes("验证码")) {
        errorMessage = "验证码错误或已过期，请重新获取";
      } else if (errorMessage.includes("邮箱")) {
        errorMessage = "邮箱已被注册或格式不正确";
      } else if (errorMessage.includes("网络")) {
        errorMessage = "网络连接失败，请检查网络设置";
      }

      message.error(errorMessage);
    } finally {
      setLoading(false);
    }
  };

  // 密码确认验证
  const validateConfirmPassword = (_: any, value: string) => {
    if (!value || form.getFieldValue("password") === value) {
      return Promise.resolve();
    }
    return Promise.reject(new Error("两次输入的密码不一致"));
  };

  // 渲染角色特定字段
  const renderRoleSpecificFields = () => {
    if (selectedRole === "teacher") {
      return (
        <>
          <Form.Item
            name="teacherNo"
            label="工号"
            rules={[{ required: true, message: "请输入教师工号" }]}
          >
            <Input placeholder="请输入教师工号" />
          </Form.Item>
          <Form.Item
            name="department"
            label="所属院系"
            rules={[{ required: true, message: "请输入所属院系" }]}
          >
            <Input placeholder="如：计算机学院" />
          </Form.Item>
          <Form.Item
            name="title"
            label="职称"
            rules={[{ required: true, message: "请输入职称" }]}
          >
            <Select placeholder="请选择职称">
              <Select.Option value="讲师">讲师</Select.Option>
              <Select.Option value="副教授">副教授</Select.Option>
              <Select.Option value="教授">教授</Select.Option>
              <Select.Option value="助教">助教</Select.Option>
            </Select>
          </Form.Item>
          <Form.Item
            name="subject"
            label="主要学科"
            rules={[{ required: true, message: "请输入主要学科" }]}
          >
            <Input placeholder="如：计算机科学与技术" />
          </Form.Item>
        </>
      );
    } else {
      return (
        <>
          <Form.Item
            name="studentId"
            label="学号"
            rules={[{ required: true, message: "请输入学号" }]}
          >
            <Input placeholder="请输入学号" />
          </Form.Item>
          <Form.Item
            name="major"
            label="专业"
            rules={[{ required: true, message: "请输入专业" }]}
          >
            <Input placeholder="如：计算机科学与技术" />
          </Form.Item>
          <Form.Item
            name="className"
            label="班级"
            rules={[{ required: true, message: "请输入班级" }]}
          >
            <Input placeholder="如：计科21-1班" />
          </Form.Item>
          <Form.Item
            name="grade"
            label="年级"
            rules={[{ required: true, message: "请输入年级" }]}
          >
            <Select placeholder="请选择年级">
              <Select.Option value="2021">2021级</Select.Option>
              <Select.Option value="2022">2022级</Select.Option>
              <Select.Option value="2023">2023级</Select.Option>
              <Select.Option value="2024">2024级</Select.Option>
            </Select>
          </Form.Item>
        </>
      );
    }
  };

  return (
    <div className="register-container">
      <Card className="register-card">
        <h2 className="register-title">用户注册</h2>

        <Form<RegisterForm>
          form={form}
          name="register"
          layout="vertical"
          onFinish={onFinish}
          initialValues={{ role: "teacher" }}
          scrollToFirstError
        >
          {/* 基本信息 */}
          <Form.Item
            name="name"
            label="姓名"
            rules={[{ required: true, message: "请输入真实姓名" }]}
          >
            <Input
              prefix={<UserOutlined />}
              placeholder="请输入真实姓名"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="phone"
            label="手机号"
            rules={[
              { required: true, message: "请输入手机号" },
              { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号" },
            ]}
          >
            <Input
              prefix={<PhoneOutlined />}
              placeholder="请输入手机号"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: "请输入邮箱" },
              { type: "email", message: "请输入正确的邮箱格式" },
            ]}
          >
            <Input
              prefix={<MailOutlined />}
              placeholder="请输入邮箱"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="role"
            label="用户角色"
            rules={[{ required: true, message: "请选择用户角色" }]}
          >
            <Select
              size="large"
              placeholder="请选择用户角色"
              onChange={(value) => setSelectedRole(value)}
            >
              <Select.Option value="teacher">教师</Select.Option>
              <Select.Option value="student">学生</Select.Option>
            </Select>
          </Form.Item>

          {/* 角色特定字段 */}
          {renderRoleSpecificFields()}

          <Form.Item
            name="password"
            label="密码"
            rules={[
              { required: true, message: "请输入密码" },
              { min: 6, message: "密码至少6位" },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请输入密码"
              size="large"
            />
          </Form.Item>

          <Form.Item
            name="confirmPassword"
            label="确认密码"
            dependencies={["password"]}
            rules={[
              { required: true, message: "请确认密码" },
              { validator: validateConfirmPassword },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined />}
              placeholder="请再次输入密码"
              size="large"
            />
          </Form.Item>

          {/* 图形验证码 */}
          <Form.Item
            name="captcha"
            label="图形验证码"
            rules={[{ required: true, message: "请输入图形验证码" }]}
          >
            <Row gutter={8}>
              <Col span={14}>
                <Input
                  prefix={<SafetyOutlined />}
                  placeholder="请输入图形验证码"
                  size="large"
                />
              </Col>
              <Col span={6}>
                <img
                  src={captchaUrl}
                  alt="验证码"
                  className="captcha-image"
                  onClick={loadCaptcha}
                  title="点击刷新验证码"
                />
              </Col>
              <Col span={4}>
                <Button
                  icon={<ReloadOutlined />}
                  onClick={loadCaptcha}
                  size="large"
                  title="刷新验证码"
                />
              </Col>
            </Row>
          </Form.Item>

          {/* 短信验证码 */}
          <Form.Item
            name="smsCode"
            label="短信验证码"
            rules={[{ required: true, message: "请输入短信验证码" }]}
          >
            <Row gutter={8}>
              <Col span={16}>
                <Input
                  prefix={<SafetyOutlined />}
                  placeholder="请输入短信验证码"
                  size="large"
                />
              </Col>
              <Col span={8}>
                <Button
                  onClick={sendSmsCode}
                  loading={sendingCode}
                  disabled={countdown > 0}
                  size="large"
                  block
                >
                  {countdown > 0 ? `${countdown}秒后重发` : "获取验证码"}
                </Button>
              </Col>
            </Row>
          </Form.Item>

          {/* 用户协议 */}
          <Form.Item
            name="agree"
            valuePropName="checked"
            rules={[
              {
                validator: (_, value) =>
                  value
                    ? Promise.resolve()
                    : Promise.reject(new Error("请同意用户协议")),
              },
            ]}
          >
            <Checkbox>
              我已阅读并同意
              <Button
                type="link"
                onClick={() => setAgreementVisible(true)}
                style={{ padding: 0, margin: 0 }}
              >
                《用户协议》
              </Button>
            </Checkbox>
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              size="large"
              loading={loading}
              className="register-button"
            >
              注册
            </Button>
          </Form.Item>
        </Form>

        <div className="login-link">
          已有账号？
          <Link to="/login">立即登录</Link>
        </div>
      </Card>

      {/* 用户协议Modal */}
      <Modal
        title="用户协议"
        open={agreementVisible}
        onCancel={() => setAgreementVisible(false)}
        footer={[
          <Button
            key="ok"
            type="primary"
            onClick={() => setAgreementVisible(false)}
          >
            我已了解
          </Button>,
        ]}
        width={600}
      >
        <div style={{ maxHeight: "400px", overflowY: "auto", padding: "16px" }}>
          <h3>教学管理系统用户协议</h3>
          <p>
            欢迎使用教学管理系统！本协议旨在规范用户的使用行为，保护系统安全和用户权益。
          </p>

          <h4>1. 服务说明</h4>
          <p>教学管理系统为教师和学生提供在线教学、学习管理等服务。</p>

          <h4>2. 用户责任</h4>
          <ul>
            <li>提供真实、准确的个人信息</li>
            <li>妥善保管账号密码，不得转让给他人使用</li>
            <li>遵守系统使用规范，不得进行违法违规操作</li>
            <li>尊重他人知识产权，不得传播不当内容</li>
          </ul>

          <h4>3. 隐私保护</h4>
          <p>我们承诺保护用户隐私，不会未经授权泄露用户个人信息。</p>

          <h4>4. 服务变更</h4>
          <p>系统保留随时修改或终止服务的权利，重要变更将提前通知用户。</p>

          <h4>5. 免责声明</h4>
          <p>
            用户使用系统产生的风险由用户自行承担，系统不承担因不可抗力导致的损失。
          </p>

          <p style={{ marginTop: "20px", color: "#666" }}>
            <small>本协议最终解释权归教学管理系统所有。</small>
          </p>
        </div>
      </Modal>
    </div>
  );
};

export default Register;
